﻿using UnityEngine;
using System.Collections;

public class SoulMonsterController : MonoBehaviour {

    public CharacterController m_cc;

    private Animator m_anim;

    private Transform player;

    public float Distancer = 0.7f;

    public float speed = 3;

    private bool XK = true;

    public float timer = 0;

    public float time = 2;

    private PlayerAttackAndDamage playerAttack;
	// Use this for initialization
	void Start () {
	 m_cc=GetComponent<CharacterController>();
     m_anim = GetComponent<Animator>();
     player = GameObject.FindGameObjectWithTag("Player").transform;
        playerAttack=player.GetComponent<PlayerAttackAndDamage>();
	}
	
	// Update is called once per frame
	void Update () {


            if (playerAttack.hp <= 0)
            {
                m_anim.SetBool("Run", false);
                return;
            }


        float distance = 0;
        if (player)
        {
            Vector3 tgp = player.position;

           transform.LookAt(tgp);



            tgp.y = transform.position.y;

            distance = Vector3.Distance(player.position, transform.position);
        }

        timer += Time.deltaTime;
        if (timer >= time)
        {
            XK = true;
            timer = 0;
        }

        if (m_anim.GetCurrentAnimatorStateInfo(0).IsName("MonAttack"))
        {
            m_anim.SetBool("Run", false);
        }

        if (distance >= Distancer)
        {

            if (!(m_anim.GetCurrentAnimatorStateInfo(0).IsName("MonAttack") || m_anim.GetCurrentAnimatorStateInfo(0).IsName("MonDefeat") ) )
            {
                m_cc.SimpleMove(transform.forward * speed);
                m_anim.SetBool("Run", true);
              
            }

        }
        else
        {
            if (XK)
            {
                m_anim.SetTrigger("MonAttack");
                XK = false;
                timer = 0;

            }
        }

	}
}
